/**
 * 
 */
package edu.usc.imsc.icampus.client.activities;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; 


import com.usc.nearbyus.Nearbyus;
import com.usc.nearbyus.R;

import android.R.xml;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import edu.usc.imsc.icampus.android.client.comm.ServerConnection;
import edu.usc.imsc.icampus.android.client.comm.WiFiConnection;
import edu.usc.imsc.icampus.android.client.enums.ServerCommand;
import edu.usc.imsc.icampus.android.client.listeners.ServerResponseListener;


/**
 * @author pranav
 *
 */
public class SubmitData extends Activity implements ServerResponseListener{


	private String TAG = "SubmitData";


	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.submitdata);

		/*	submitReadings = (Button)findViewById(R.id.submitreadings);
		queryData = (Button) findViewById(R.id.querydata);

		submitReadings.setOnClickListener(this);
		queryData.setOnClickListener(this);*/
	}


	/**
	 * 
	 * @return -- true if wifi is connected, false otherwise
	 */
	public boolean isWiFiConnected() {
		WiFiConnection instance = WiFiConnection.getInstance(this.getApplicationContext());
		return instance.isWiFiConnected();
	}
	public void retrieveAllWiFi(View v) throws Exception {
		WiFiConnection instance = WiFiConnection.getInstance(SubmitData.this);
		if(!instance.isWiFiConnected()){

			Toast.makeText(this.getBaseContext()
					, "Check your WiFi connection please!", Toast.LENGTH_SHORT).show();
			return;
		}
		ServerConnection serverConn;
		serverConn = ServerConnection.getInstance(this.getBaseContext());
		serverConn.getAllWiFi(this, ServerCommand.QUERY_ALL_WIFI_SIGNAL);

	}


	public void sendXMLToServer(View v) throws Exception {


		WiFiConnection instance = WiFiConnection.getInstance(SubmitData.this);
		if(!instance.isWiFiConnected()){
			Toast.makeText(this.getBaseContext()
					, "Check your WiFi connection please!", Toast.LENGTH_SHORT).show();
			return;
		}

		File readingFile = new File(Environment.getExternalStorageDirectory(), "nearbyus/readings.xml");
		InputStream is = new FileInputStream(readingFile);
		Log.d(TAG,"XML is available : "+is.available());
		char[] buffer = new char[is.available()];
		Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
		reader.read(buffer);
		String xmlstr = String.valueOf(buffer);
		Log.d(TAG, "XML : "+xmlstr);

		sendXMLtoNearbyUS(xmlstr);

		//	sendXMLtoICampus(xmlstr);		

		is.close();

	}	


	/**
	 * This method submits the readings data collected in xml file on external storage(sd card) to ICampusServers
	 * 
	 * @param xmlstr
	 */
	private void sendXMLtoICampus(String xmlstr){

		Log.d(TAG, "XML Submit to ICampus servers");

		ServerConnection serverConn;
		try {
			serverConn = ServerConnection.getInstance(this.getBaseContext());
			serverConn.addWiFiSignal(xmlstr, this, ServerCommand.ADDWIFISIGNAL);

		} catch (Exception e) {
			throw new RuntimeException("SendXML to ICampus server failed : " ,e);
		}		

	}

	/**
	 * This method submits the data to NearbyUS servers
	 * @param xmlstr2
	 */
	private void sendXMLtoNearbyUS(String xmlstr) {

		Log.d(TAG, "XML Submit to nearbyUS servers");

		String urlNearbyUS = "http://nearbyus.org/UploadNearbyData.php";			

		try {

			File readingFile = new File(Environment.getExternalStorageDirectory(), "nearbyus/readings.xml");		

			
			HttpClient client = new DefaultHttpClient(); 
			httpPostFileUpload(client, readingFile.getPath(), urlNearbyUS, "myfile"); 
			
			/*
			 * 
			 * This code doesn't work ... :( so do not bother using it for XML submission
			 * 
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(urlNearbyUS);	
			StringEntity se = new StringEntity( xmlstr, HTTP.UTF_8);
			 
	        se.setContentType("text/xml");
	        httppost.setEntity(se);
			
			HttpResponse httpresponse = httpClient.execute(postRequest);
	        HttpEntity resEntity = httpresponse.getEntity();   	       
	        Log.d(TAG, "HttpResponse Entity from nearByUS : " + EntityUtils.toString(httpresponse.getEntity()));
			 */
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	 
		catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


	}


	

	/**
	 * 
	 * @param client
	 * @param filePath
	 * @param uploadUri
	 * @param inputNameAttr
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public void httpPostFileUpload( HttpClient client, String filePath, String uploadUri, 
			String inputNameAttr) throws ClientProtocolException,IOException { 
		
		HttpUriRequest request = new HttpPost(uploadUri); 
		MultipartEntity form = new MultipartEntity(); 
		// disable expect-continue handshake (lighttpd doesn't support it) 
		client.getParams().setBooleanParameter( 
				"http.protocol.expect-continue", false); 
		form.addPart(inputNameAttr, new FileBody(new File(filePath))); 
		((HttpEntityEnclosingRequestBase)request).setEntity(form); 
		try { 			 
			HttpResponse httpresponse = client.execute(request);
	        HttpEntity resEntity = httpresponse.getEntity();   	       
	        Log.d(TAG, "HttpResponse from nearByUS Server upon XML submission : " + EntityUtils.toString(httpresponse.getEntity()));
		} catch (ClientProtocolException e) { 
			throw e; 
		} catch (IOException ee) { 
			throw ee; 
		} 
	} 



	@Override
	public void onServerResponse(ServerCommand arg0, int arg1, Object arg2) {
		Log.d(TAG, "onServerResponse : " + "responseCode="+arg1);
		if (arg1 == 200) {
			switch (arg0) {
			case QUERY_ALL_WIFI_SIGNAL:
				Log.d(TAG , "Query Result : "+(String)arg2);
				//the result is in arg2 (xml string)
				break;
			default:
				Log.e(TAG, "ServerCommand not recognized");
				break;
			}
		} else {
			Log.d(TAG, "Response Code : "+arg1+ " error");
		}

	}

	/*
	@Override
	public void onClick(View v) {

		switch(v.getId()){
		case R.id.submitreadings:
			try {
				sendXMLToServer(v);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;			
		case R.id.querydata:
			break;
		}
	}
	 */

}
